package com.authapi.sample.api.annotation;

import com.authapi.sample.api.model.Exception.PermissionDeniedException;
import com.authapi.sample.api.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Aspect
@Slf4j
public class AnnotationAspect {
    @Autowired
    TokenUtil tokenUtil;
    @Qualifier("httpServletRequest")
    @Autowired
    private ServletRequest httpServletRequest;
    @Autowired
    private HttpServletResponse httpServletResponse;

    @Pointcut("@annotation(com.authapi.sample.api.annotation.AdminOnly)")
    public void cutMethod(){

    }
    /**
     * 切点之前
     */
    @Before("cutMethod()")
    public void before(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String  token = request.getHeader("token");
            var tokenMap = tokenUtil.parseToken(token);
            String admin = tokenMap.get("isAdmin");
            if(admin.equals("0")){
                httpServletResponse.sendError(403,"需要管理员权限");
                throw new RuntimeException("Add user is prevented due to certain conditions.");
            }
        }

    }
}
